import cv2
import pyautogui
import numpy as np
import time
import sys

class App:
    def __init__(self, file_path: str, interval):
        self.file_path = ''.join(c for c in file_path if c.isprintable())  # 去除路径中的不可见字符
        self.interval = interval
        self.running = False

    def start(self):
        if not self.file_path:
            print("Please upload a file first.")
            return
        
        self.running = True
        self.update_log("Started.")
        self.process_image()

    def pause(self):
        self.running = False
        self.update_log("Paused.")

    def process_image(self):
        while self.running:
            # 读取屏幕截图
            screenshot = pyautogui.screenshot()
            screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)

            # 读取模板图像
            with open(self.file_path, 'rb') as f:
                file_bytes = np.asarray(bytearray(f.read()), dtype=np.uint8)
                template = cv2.imdecode(file_bytes, cv2.IMREAD_GRAYSCALE)
            
            if template is None:
                print(f"Error: Unable to read the template image from {self.file_path}")
                return

            template_w, template_h = template.shape[::-1]
            # 转换截图为灰度图像
            gray_screenshot = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)

            # 匹配模板
            res = cv2.matchTemplate(gray_screenshot, template, cv2.TM_CCOEFF_NORMED)
            min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

            # 设置匹配阈值
            threshold = 0.8
            if max_val >= threshold:
                top_left = max_loc
                bottom_right = (top_left[0] + template_w, top_left[1] + template_h)
                center_x = top_left[0] + template_w // 2
                center_y = top_left[1] + template_h // 2
                pyautogui.doubleClick(center_x, center_y) # 双击
                self.update_log("double clicked!")
            else:
                self.update_log("Image not found on the screen.")
            
            time.sleep(self.interval)

    def update_log(self, message):
        print(message)

if __name__ == "__main__":
    file_path = input("请输入要上传的文件路径: ")
    print(file_path)
    interval = int(input("请输入频率 (秒): "))
    app = App(file_path, interval)
    try:
        app.start()
    except KeyboardInterrupt:
        app.pause()
        print("程序已停止.")